import express from "express";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import { getDb } from "../config/database.js";
import authMiddleware from "../middleware/auth.js";

const router = express.Router();
const JWT_SECRET = process.env.JWT_SECRET || "your-jwt-secret-key";

// 用户登录
router.post("/login", async (req, res) => {
  try {
    const { username, password } = req.body;

    // 验证输入
    if (!username || !password) {
      return res.status(400).json({ error: "用户名和密码不能为空" });
    }

    const db = getDb();
    const users = db.collection("users");

    // 查找用户
    const user = await users.findOne({ username });
    if (!user) {
      return res.status(401).json({ error: "用户名或密码错误" });
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      return res.status(401).json({ error: "用户名或密码错误" });
    }

    // 生成 JWT token
    const token = jwt.sign(
      {
        userId: user._id,
        username: user.username,
        role: user.role,
      },
      JWT_SECRET,
      { expiresIn: "24h" }
    );

    // 记录登录日志
    await users.updateOne(
      { _id: user._id },
      {
        $set: { lastLoginAt: new Date() },
        $inc: { loginCount: 1 },
      }
    );

    res.json({
      message: "登录成功",
      token,
      user: {
        id: user._id,
        username: user.username,
        email: user.email,
        role: user.role || "user",
        lastLoginAt: new Date(),
      },
    });
  } catch (error) {
    console.error("登录错误:", error);
    res.status(500).json({ error: "服务器内部错误" });
  }
});

// 验证令牌
router.get("/verify", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const users = db.collection("users");

    const user = await users.findOne({ _id: req.user.userId });
    if (!user) {
      return res.status(404).json({ error: "用户不存在" });
    }

    res.json({
      user: {
        id: user._id,
        username: user.username,
        email: user.email,
        role: user.role || "user",
        lastLoginAt: user.lastLoginAt,
      },
    });
  } catch (error) {
    console.error("令牌验证错误:", error);
    res.status(500).json({ error: "服务器内部错误" });
  }
});

// 获取用户列表（管理员功能）
router.get("/users", authMiddleware, async (req, res) => {
  try {
    if (req.user.role !== "admin") {
      return res.status(403).json({ error: "权限不足" });
    }

    const db = getDb();
    const users = db.collection("users");

    const userList = await users
      .find(
        {},
        {
          projection: {
            password: 0, // 不返回密码字段
          },
        }
      )
      .toArray();

    res.json({
      users: userList,
      total: userList.length,
    });
  } catch (error) {
    console.error("获取用户列表错误:", error);
    res.status(500).json({ error: "服务器内部错误" });
  }
});

export default router;
